package com.gary.demo.biz.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gary.demo.biz.ProductBO;
import com.gary.demo.common.model.LoginHolder;
import com.gary.demo.common.utils.CheckUtil;
import com.gary.demo.dao.ProductMapper;
import com.gary.demo.entity.Product;
import com.gary.demo.model.param.ProductOperateParam;
import com.gary.demo.model.param.ProductQueryParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductBOImpl implements ProductBO {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private LoginHolder loginHolder;

    @Override
    public Integer add(ProductOperateParam param) {
        Product product = new Product();
        BeanUtils.copyProperties(param, product);
        product.setCreator(loginHolder.currentUser().getUserName());
        productMapper.insert(product);
        return product.getId();
    }

    @Override
    public void update(ProductOperateParam param) {
        Product product = productMapper.selectById(param.getId());
        CheckUtil.isNull(product, "未查询到对应的产品信息");
        Product updateProduct = new Product();
        BeanUtils.copyProperties(param,updateProduct);
        updateProduct.setModifier(loginHolder.currentUser().getUserName());
        productMapper.updateById(updateProduct);
    }

    @Override
    public Product getById(Integer id) {
        return productMapper.selectById(id);
    }

    @Override
    public IPage<Product> pageQuery(ProductQueryParam param) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(param.getProductName())) {
            queryWrapper.like(Product::getProductName, param.getProductName());
        }
        if (StrUtil.isNotBlank(param.getCreator())) {
            queryWrapper.eq(Product::getCreator, param.getCreator());
        }
        IPage<Product> page = new Page<>(param.getPageNum(), param.getPageSize());
        return productMapper.selectPage(page, queryWrapper);
    }
}
